import api from "~/utils/api";
import utils from "@/utils/utils";

export default {
  namespaced: true,
  state: () => ({
    navbar: [],
    category: [],
    carousel: [],
    hot: [],
    noAnswer: [],
    user: null,
    userRecommend: [],
  }),
  mutations: {
    setNavbar(state, val) {
      state.navbar = val;
    },
    setCategory(state, val) {
      state.category = val;
    },
    setCarousel(state, val) {
      state.carousel = val;
    },
    setUser(state, val) {
      state.user = val;
    },
    logout(state, val) {
      state.user = null;
    },
    setNoAnswer(state, val) {
      state.noAnswer = val;
    },
    setHot(state, val) {
      state.hot = val;
    },
    setUserRecommend(state, val) {
      state.userRecommend = val;
    },
  },
  actions: {
    async nuxtServerInit({commit}, {req}) {
      let token = utils.getCookie('token', req.headers.cookie);
      if (token) {
        //登录
        try {
          let user = await api.getUser(token);
          if (user) {
            commit('setUser', user);
          }
        } catch (e) {
          console.error(e);
        }
      }
      let navbar = await api.getNavbar();
      //菜单
      commit('setNavbar', navbar);

      //热门
      let hot = await api.getTopicHot();
      commit('setHot', hot);

      //没人回答的
      let noAnswer = await api.getTopicNoAnswer();
      commit('setNoAnswer', noAnswer);

    }
  }
}
